﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Xml;

namespace GianosNET.Common.Classes
{
    public class ModuleConfigSection : IConfigurationSectionHandler
    {
        #region Subclasses
        public class ModuleConfiguration
        {
            public string AssemblyPath { get; set; }
            public string AssemblyTypeName { get; set; }
            public string Name { get; set; }
            public string ConfigArea { get; set; }

            public bool AutoDiscovered { get; set; }
        }

        public class ModuleConfigurations : List<ModuleConfiguration>
        {
            
        }
        #endregion

        public ModuleConfigurations Config { get; private set; }


        public ModuleConfigSection()
        {
            Config = new ModuleConfigurations();
        }

        public object Create(object parent, object configContext, XmlNode section)
        {
            DictionarySectionHandler tmp = new DictionarySectionHandler();
            if (section == null) 
                return null;

            ModuleConfigSection res = new ModuleConfigSection();
            
            foreach (XmlNode node in section.ChildNodes)
            {
                if (node is XmlElement && node.Name.ToLower() == "add")
                {
                    XmlElement el = node as XmlElement;

                    string name = el.GetAttribute("name");
                    if (string.IsNullOrEmpty(name))
                        throw new Exception("Errore nel file di configurazione");

                    if (res.Config.Exists(c=>c.Name.ToLower() == name.ToLower()))
                        throw new Exception("Errore nel file di configurazione: nome duplicato");

                    ModuleConfiguration cfg = new ModuleConfiguration
                    {
                        Name = name,
                        AssemblyPath = el.GetAttribute("assemblyPath"),
                        AssemblyTypeName = el.GetAttribute("assemblyTypeName"),
                        ConfigArea = el.GetAttribute("configArea")
                    };

                    res.Config.Add(cfg);
                }
            }

            return res;
        }
    }
}
